<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建指标下降目标' : '编辑指标下降目标') + ''"
    width="800px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import { add, edit, detail } from "@/api/energyConservation/set.js";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import {
  deepClone,
  replaceDigit,
  replaceInteger,
  dealElectricity,
} from "@/utils/index";

export default {
  dicts: [],
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      areaIdarr: [],
      areaProps: {
        value: "id",
        children: "children",
        label: "label",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      apsForm: {
        formRef: "form",
        formData: {},
        labelWidth: "auto",
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              areaId: [
                {
                  required: true,
                  message: "请选择区域",
                  trigger: "change",
                },
              ],
              year: [
                {
                  required: true,
                  message: "请选择适用年份",
                  trigger: "change",
                },
              ],
              areaUnitEnergyRangePercent: [
                {
                  required: true,
                  message: "请输入正确的单位面积综合能耗",
                  trigger: "blur",
                },
              ],
              personalEnergyRangePercent: [
                {
                  required: true,
                  message: "请输入正确的人均综合能耗",
                  trigger: "blur",
                },
              ],
              personalWaterRangePercent: [
                {
                  required: true,
                  message: "请输入正确的人均水耗",
                  trigger: "blur",
                },
              ],
              personalDcRangePercent: [
                {
                  required: true,
                  message: "请输入正确的碳排放量",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            areaId: {
              label: "区域",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().areaId;
                let a = (
                  <CascaderSelect
                    values={valNum}
                    value={valNum}
                    requestMethod={"get"}
                    varient={"areaDept"}
                    propOptions={that.areaProps}
                    size={"small"}
                    placeholder={"请选择区域"}
                    onInput={(value) => {
                      if (value && value.length > 0) {
                        this.$refs?.form?.setFieldValue(
                          "areaId",
                          value[value.length - 1]
                        );
                      } else {
                        this.$refs?.form?.setFieldValue("areaId", null);
                      }
                    }}
                  ></CascaderSelect>
                );
                return <div>{a}</div>;
              },
            },
            year: {
              label: "适用年份",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              placeholder: "选择适用年份",
              "value-format": "yyyy",
            },
            areaUnitEnergyRangePercent: {
              label: "单位面积综合能耗(kgce/m2)",
              render: (h) => {
                let that = this;
                let unit = "%";
                let a = (
                  <el-input
                    value={
                      that.$refs?.form?.getFieldsValue()
                        .areaUnitEnergyRangePercent
                    }
                    size="small"
                    placeholder="请输入单位面积综合能耗"
                    clearable
                    onInput={(val) =>
                      that.replaceDigitDeal(
                        val,
                        2,
                        "areaUnitEnergyRangePercent"
                      )
                    }
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
            personalEnergyRangePercent: {
              label: "人均综合能耗(kgce/p)",
              render: (h) => {
                let that = this;
                let unit = "%";
                let a = (
                  <el-input
                    value={
                      that.$refs?.form?.getFieldsValue()
                        .personalEnergyRangePercent
                    }
                    size="small"
                    placeholder="请输入人均综合能耗"
                    clearable
                    onInput={(val) =>
                      that.replaceDigitDeal(
                        val,
                        2,
                        "personalEnergyRangePercent"
                      )
                    }
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
            personalWaterRangePercent: {
              label: "人均水耗(t/p)",
              render: (h) => {
                let that = this;
                let unit = "%";
                let a = (
                  <el-input
                    value={
                      that.$refs?.form?.getFieldsValue()
                        .personalWaterRangePercent
                    }
                    size="small"
                    placeholder="请输入人均水耗"
                    clearable
                    onInput={(val) =>
                      that.replaceDigitDeal(val, 2, "personalWaterRangePercent")
                    }
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
            personalDcRangePercent: {
              label: "碳排放量(kgCO2)",
              render: (h) => {
                let that = this;
                let unit = "%";
                let a = (
                  <el-input
                    value={
                      that.$refs?.form?.getFieldsValue().personalDcRangePercent
                    }
                    size="small"
                    placeholder="请输入碳排放量"
                    clearable
                    onInput={(val) =>
                      that.replaceDigitDeal(val, 2, "personalDcRangePercent")
                    }
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    getInfo() {
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.year = newData.year + "";
          newData.areaUnitEnergyRangePercent =
          (newData.areaUnitEnergyRangePercent * 100).toFixed(2);
          newData.personalDcRangePercent =
            (newData.personalDcRangePercent * 100).toFixed(2);
          newData.personalEnergyRangePercent =
            (newData.personalEnergyRangePercent * 100).toFixed(2)
          newData.personalWaterRangePercent =
            (newData.personalWaterRangePercent * 100).toFixed(2);
          this.areaIdarr = newData.areaId;
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    submit() {
      const info = this.$refs.form.getFieldsValue();
      const data = {
        id: this.id,
        areaId: info.areaId,
        year: info.year,
        areaUnitEnergyRangePercent: info.areaUnitEnergyRangePercent / 100,
        personalDcRangePercent: info.personalDcRangePercent / 100,
        personalEnergyRangePercent: info.personalEnergyRangePercent / 100,
        personalWaterRangePercent: info.personalWaterRangePercent / 100,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      add(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    editRequest(data) {
      edit(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /* 输入限制 */
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      let result = replaceDigit(val, dit);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      let result = replaceInteger(val);
      this.$refs?.form?.setFieldValue(flage, result);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
